package app.modules.account.persistence.dao;

import app.modules.account.persistence.mapper.UserRoleRelationMapper;
import app.modules.security.dto.web.role.WebRoleDTO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jasmine.framework.database.mybatisplus.dao.BaseEntityDAO;
import jasmine.security.rbac.model.SecUserRoleRelation;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author mh.z
 */
@Repository
public class UserRoleRelationDAO extends BaseEntityDAO<UserRoleRelationMapper, SecUserRoleRelation> {

    /**
     * 查询指定用户的所有已分配角色
     *
     * @param userId
     * @return
     */
    public List<WebRoleDTO> listAssignedRoles(Long userId) {
        return baseMapper.listAssignedRoles(userId);
    }

    /**
     * 删除指定用户的所有角色分配关系
     *
     * @param userId
     */
    public void deleteByUserId(Long userId) {
        LambdaQueryWrapper<SecUserRoleRelation> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(SecUserRoleRelation::getUserId, userId);

        baseMapper.delete(wrapper);
    }

    /**
     * 统计指定角色共分配给多少用户
     *
     * @param roleId
     * @return
     */
    public long countByRoleId(Long roleId) {
        LambdaQueryWrapper<SecUserRoleRelation> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(SecUserRoleRelation::getRoleId, roleId);

        return baseMapper.selectCount(wrapper);
    }

}
